﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Downplay.Mechanics.Impulses.Services;
using Orchard.Environment.Extensions;

namespace Downplay.Mechanics.Controllers
{
    [OrchardFeature("Downplay.Mechanics.Impulses")]
    public class ImpulseController : Controller
    {
        private IImpulseService _impulseService;

        public ImpulseController(
            IImpulseService impulseService)
        {
            _impulseService = impulseService;
        }

        public ActionResult Actuate(string prefix, string name, int sourceId,string returnUrl)
        {

            var impulse = _impulseService.CheckForImpulse(prefix, name, sourceId);
            if (impulse == null)
            {
                return HttpNotFound("Could not actuate impulse");
            }
            var context = new ImpulseContext()
            {
                Impulse = impulse,
                ReturnUrl = returnUrl
            };
            var result = _impulseService.ActuateImpulse(context);
            if (result == ImpulseActuationResult.NotAuthorized)
            {
                return new HttpUnauthorizedResult();
            }
            // Back to origin page (or other as defined in context)
            return Redirect(context.ReturnUrl);
        }

    }
}